package controllers;

import play.i18n.Lang;
import play.libs.OpenID;
import play.mvc.Before;
import play.mvc.Controller;

public class DemoController extends Controller {
    @Before(unless={"login", "authenticate"})
    static void checkAuthenticated() {
        if(!session.contains("user")) {
            login();
        }
    }

    public static void index() {
        render("Hello %s!", session.get("user"));
    }

    public static void login() {
        // 实现国际化
        Lang.change("en");

        render();
    }

    public static void authenticate(String user) {
        if(OpenID.isAuthenticationResponse()) {
            OpenID.UserInfo verifiedUser = OpenID.getVerifiedID();
            if(verifiedUser == null) {
                flash.error("Oops. Authentication has failed");
                login();
            }
            session.put("user", verifiedUser.id);
            index();
        } else {
            // will redirect the user
            if(!OpenID.id(user).verify()) {
                flash.error("Cannot verify your OpenID");
                login();
            }
        }
    }
}
